use std::env::args;
use std::ffi::CString;
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;
use std::thread::sleep;
use nix::libc::{__errno_location, exit, printf, rmdir, strerror};
use crate::utilty::log_error;

pub fn wrap_kill(){
    if args().count()<3{
        log_error("args count error".to_string());
        return;
    }
    kill_container();
}
///kill a container by pid and remove cgroup of container</br>
/// 给容器的1号进程 发送sigkill信号强制终止</br>
/// 删除对应的cgroup目录</br>
/// jidocker kill <container_pid>
pub fn kill_container() {
    let pid = args().nth(2).expect("no specify pid");
    let pid = i32::from_str_radix(pid.as_str().trim(), 10).expect("kill failed");
    println!("killed {pid}");
    unsafe {
        let cgroup_pid_path = format!("/sys/fs/cgroup/my-docker-{pid}");

        match fs::exists(cgroup_pid_path.as_str()).expect("check container failed") {
            true => {
                let mut cgroup_kill = OpenOptions::new()
                    .write(true)
                    .open(format!("{}/cgroup.kill", cgroup_pid_path.clone()))
                    .expect("open /cgroup.kill failed");
                cgroup_kill
                    .write_all("1".as_bytes())
                    .expect("write cgroup kill failed");
                let c_string = CString::new(cgroup_pid_path).expect("CString::new failed");
                let mut spin_counts = 1000;
                while spin_counts >= 0 {
                    if rmdir(c_string.as_ptr()) == 0 {
                        exit(0);
                    }
                    sleep(std::time::Duration::from_millis(1));
                    spin_counts -= 1;
                }
                print!("rm cgroup_pid_path failed");
                printf(
                    c"%s ,%d\n".as_ptr(),
                    strerror(*__errno_location()),
                    *__errno_location(),
                );

            }
            false => {}
        };
    }
}